<?php
//use Util\Http;

namespace Util;

define("ACCESS_TOKEN_URL","https://api.weixin.qq.com/sns/oauth2/access_token");
define("REFRESH_TOKEN_URL","https://api.weixin.qq.com/sns/oauth2/refresh_token");
define("USERINFO_URL","https://api.weixin.qq.com/sns/userinfo");

class Wechat{
    private $appId;          //微信公众号的appId
    private $appSecret;      //微信公众号的appSecret

    /**
     * 设置appid和secret
     * @param $appId 微信公众号的appid
     * @param $appSecret 微信公众号的secret
     */
    public function setConfig($appId,$appSecret){
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    /**
     * 请求access_token
     * @param $code 从微信返回的code码
     * @return string json字符串,包含access_token,expires_in,refresh_token,openid,scope
     */
    public function requestAccessToken($code){
        $http = new Http();
        $http->setUrl(ACCESS_TOKEN_URL);
        $http->setParams(array(
            "appid" => $this->appId,
            "secret" => $this->appSecret,
            "code" => $code,
            "grant_type" => "authorization_code"
        ));
        return $http->get();
    }

    /**
     * 使用refresh_token获取access_token
     * @param $refreshToken 用户的refresh_token
     * @return string json的字符串,包含access_token,expires_in,refresh_token,openid,scope
     */
    public function requestAccessTokenByRefreshToken($refreshToken){
        $http = new Http();
        $http->setUrl(REFRESH_TOKEN_URL);
        $http->setParams(array(
            "appid" => $this->appId,
            "grant_type" => "refresh_token",
            "refresh_token" => $refreshToken
        ));
        return $http->get();
    }

    /**
     * 获取用户的信息
     * @param $code 从微信返回的code码
     * @param $lang 语言，默认是中文，中文是zh_CN,繁体是zh_TW,英语是en
     * @return mix 出错返回false, 用户信息的json字符串，包含openid,nickname,sex(值为1时是男性，值为2时是女性，值为0时是未知),province,city,country,headimgurl,privilege,unionid（只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。）
     */
    public function requestUserInfo($code,$lang = "zh_CN"){
        $access = $this->requestAccessToken($code);
        $access = json_decode($access,true);
        if(isset($access['errcode'])){
            $GLOBALS['logger']->addError('get_wechat_info_error',$access);
            return false;
        }
        $accessToken = $access['access_token'];
        $openId = $access['openid'];

        $http = new Http();
        $http->setUrl(USERINFO_URL);
        $http->setParams(array(
            "access_token" => $accessToken,
            "openid" => $openId,
            "lang" => $lang
        ));

        return $http->get();
    }

};